package com.lechi.web.service.impl;

import com.lechi.iot.android.entity.InDeviceMessage;
import com.lechi.web.common.utils.bean.BeanUtils;
import com.lechi.web.common.utils.spring.SpringUtils;
import com.lechi.web.service.IIotAndroidDeviceService;
import com.lechi.web.service.IIotOnlineLogService;
import com.lechi.web.service.IIotUpgradeLogService;
import com.lechi.web.service.IotCommand;
import com.lechi.web.system.domain.IotAndroidDeviceBo;
import com.lechi.web.system.domain.IotOnlineLog;
import com.lechi.web.system.domain.IotUpgradeLog;

import java.util.Date;
import java.util.TimerTask;

/**
 * The type Iot device commond.
 *
 * @author yangguang
 */
public class IotDeviceCommond implements IotCommand {

    /**
     * Gets upgrade log task.
     *
     * @param outDeviceCmd the out device cmd
     * @return the upgrade log task
     */
    public static TimerTask getUpgradeLogTask(InDeviceMessage outDeviceCmd) {
        IotUpgradeLog iotUpgradeLog = new IotUpgradeLog();
        BeanUtils.copyProperties(outDeviceCmd, iotUpgradeLog);
        iotUpgradeLog.setId(outDeviceCmd.getUpdateLogId());

        return new TimerTask() {
            @Override
            public void run() {
                SpringUtils.getBean(IIotUpgradeLogService.class).updateIotUpgradeLog(iotUpgradeLog);
            }
        };
    }

    /**
     * Gets device monitor task.
     *
     * @param iotAndroidDeviceBo the iot android device bo
     * @return the device monitor task
     */
    public static TimerTask getDeviceMonitorTask(IotAndroidDeviceBo iotAndroidDeviceBo) {
        return new TimerTask() {
            @Override
            public void run() {
                SpringUtils.getBean(IIotAndroidDeviceService.class).updateIotAndroidDevice(iotAndroidDeviceBo);
            }
        };
    }

    /**
     * Commond timer task.
     *
     * @param <T> the type parameter
     * @param t   the t
     * @return the timer task
     */
    @SafeVarargs
    public static <T> TimerTask commond(T... t) {
        IotOnlineLog iotOnlineLog = new IotOnlineLog();
        iotOnlineLog.setDeviceSN(String.valueOf(t[0]));
        iotOnlineLog.setStatus(Long.parseLong(String.valueOf(t[1])));
        iotOnlineLog.setUpdateTime(t.length >= 3 ? (Date) t[2] : new Date());
        return new TimerTask() {
            @Override
            public void run() {
                SpringUtils.getBean(IIotOnlineLogService.class).insertIotOnlineLog(iotOnlineLog);
            }
        };
    }
}
